<template>
  <div class="house-detail-container">
    <!-- Header Section -->
    <div class="header">
      <el-button type="text" @click="goBack" class="back-button">
        <el-icon><arrow-left /></el-icon> 返回列表
      </el-button>
      <h1 class="title">{{ house.house?.title || '房源详情' }}</h1>
      <div class="status-tag">
        <el-tag :type="getStatusTagType(house.house?.status)" size="large">
          {{ getStatusLabel(house.house?.status) }}
        </el-tag>
      </div>
    </div>

    <!-- Main Content -->
    <div class="content-wrapper">
      <el-tabs type="border-card" class="content-tabs">
        <!-- Basic Info Tab -->
        <el-tab-pane label="基础信息">
          <div class="tab-content">
            <div class="image-section">
              <el-carousel :interval="5000" arrow="always" height="400px" indicator-position="outside">
                <el-carousel-item v-for="(image, index) in galleryImages" :key="index">
                  <el-image
                      :src="image.image_url"
                      fit="cover"
                      style="width: 100%; height: 100%"
                      :preview-src-list="getAllImages()"
                      :initial-index="index"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><picture /></el-icon>
                        <span>图片加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div v-if="image.is_cover" class="cover-badge">封面</div>
                </el-carousel-item>
              </el-carousel>
            </div>

            <div class="info-grid">
              <div class="info-item">
                <label>物业类型</label>
                <div>{{ house.house?.property_type || '-' }}</div>
              </div>
              <div class="info-item">
                <label>租赁类型</label>
                <div>{{ house.house?.rental_type || '-' }}</div>
              </div>
              <div class="info-item">
                <label>面积</label>
                <div>{{ house.house?.area || '-' }} ㎡</div>
              </div>
              <div class="info-item">
                <label>价格</label>
                <div>{{ house.house?.price || '-' }} 元/月</div>
              </div>
              <div class="info-item">
                <label>押金</label>
                <div>{{ house.house?.deposit || '-' }} 元</div>
              </div>
              <div class="info-item">
                <label>卧室</label>
                <div>{{ house.house?.bedroom_count || '0' }} 间</div>
              </div>
              <div class="info-item">
                <label>客厅</label>
                <div>{{ house.house?.livingroom_count || '0' }} 间</div>
              </div>
              <div class="info-item">
                <label>卫生间</label>
                <div>{{ house.house?.bathroom_count || '0' }} 间</div>
              </div>
            </div>

            <div class="description-section">
              <h3>房源描述</h3>
              <div class="description-content">
                {{ house.house?.description || '暂无描述信息' }}
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- Address Info Tab -->
        <el-tab-pane label="地址信息">
          <div class="tab-content">
            <div class="address-section">
              <div class="address-item">
                <label>省份</label>
                <div>{{ house.address?.province || '-' }}</div>
              </div>
              <div class="address-item">
                <label>城市</label>
                <div>{{ house.address?.city || '-' }}</div>
              </div>
              <div class="address-item">
                <label>区县</label>
                <div>{{ house.address?.district || '-' }}</div>
              </div>
              <div class="address-item">
                <label>街道</label>
                <div>{{ house.address?.street || '-' }}</div>
              </div>
              <div class="address-item full-width">
                <label>详细地址</label>
                <div>{{ house.address?.detail || '-' }}</div>
              </div>
            </div>

            <div class="map-container">
              <div class="map-placeholder">
                <el-icon><map-location /></el-icon>
                <span>地图位置</span>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- Facility Info Tab -->
        <el-tab-pane label="设施信息">
          <div class="tab-content">
            <div class="facility-grid">
              <div v-for="(value, key) in house.facility" :key="key" class="facility-item">
                <el-icon :class="{'available': value, 'unavailable': !value}">
                  <component :is="getFacilityIcon(key)" />
                </el-icon>
                <span :class="{'available': value, 'unavailable': !value}">
                  {{ getFacilityLabel(key) }}
                </span>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- Reviews Tab -->
        <el-tab-pane label="评论">
          <div class="tab-content">
            <div class="review-section">
              <div v-if="house.reviews?.items?.length > 0">
                <div v-for="review in house.reviews.items" :key="review.review_id" class="review-item">
                  <div class="review-header">
                    <div class="user-info">
                      <span class="user-name">用户{{ review.user_id }}</span>
                      <el-rate
                          v-model="review.overall_rating"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value} 分"
                      />
                    </div>
                    <div class="review-time">{{ formatReviewTime(review.review_time) }}</div>
                  </div>
                  <div class="review-comment">{{ review.comment || '暂无评论内容' }}</div>
                  <div class="detail-ratings" v-if="review.ratings">
                    <span>清洁: {{ review.ratings.cleanliness }}分</span>
                    <span>位置: {{ review.ratings.location }}分</span>
                    <span>设施: {{ review.ratings.facility }}分</span>
                    <span>性价比: {{ review.ratings.value }}分</span>
                    <span>沟通: {{ review.ratings.communication }}分</span>
                  </div>
                </div>

                <el-pagination
                    v-if="house.reviews.pages > 1"
                    @current-change="handlePageChange"
                    :current-page="house.reviews.current_page"
                    :page-size="house.reviews.per_page || 5"
                    :total="house.reviews.total"
                    layout="prev, pager, next"
                />
              </div>
              <div v-else class="no-reviews">
                <el-empty description="暂无评论" />
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- Action Buttons -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleSubmitApplication" size="large">提交申请</el-button>
        <el-button type="success" @click="showReviewDialog = true" size="large">发表评论</el-button>
      </div>
    </div>

    <!-- Review Dialog -->
    <el-dialog v-model="showReviewDialog" title="发表评论" width="50%">
      <el-form :model="reviewForm" label-width="120px">
        <el-form-item label="清洁评分" required>
          <el-rate
              v-model="reviewForm.cleanliness_rating"
              :max="5"
              show-text
              :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <el-form-item label="位置评分" required>
          <el-rate
              v-model="reviewForm.location_rating"
              :max="5"
              show-text
              :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <el-form-item label="设施评分" required>
          <el-rate
              v-model="reviewForm.facility_rating"
              :max="5"
              show-text
              :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <el-form-item label="性价比评分" required>
          <el-rate
              v-model="reviewForm.value_rating"
              :max="5"
              show-text
              :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <el-form-item label="沟通评分" required>
          <el-rate
              v-model="reviewForm.communication_rating"
              :max="5"
              show-text
              :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <el-form-item label="评论内容">
          <el-input
              v-model="reviewForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入您的详细评价"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交评论</el-button>
      </template>
    </el-dialog>

    <!-- Order Dialog -->
    <el-dialog v-model="showOrderDialog" title="创建租赁订单" width="50%">
      <el-form :model="orderForm" label-width="120px">
        <el-form-item label="房源信息">
          <div>{{ house.house?.title }}</div>
          <div>月租金: {{ house.house?.price }} 元</div>
        </el-form-item>

        <el-form-item label="租赁开始日期" required>
          <el-date-picker
              v-model="orderForm.start_date"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              :disabled-date="(date) => date < new Date()"
          />
        </el-form-item>

        <el-form-item label="租赁结束日期" required>
          <el-date-picker
              v-model="orderForm.end_date"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="(date) => date <= new Date(orderForm.start_date)"
          />
        </el-form-item>

        <el-form-item label="租赁天数">
          <div>{{ rentalDays }} 天</div>
        </el-form-item>

        <el-form-item label="押金">
          <div>{{ orderForm.deposit }} 元</div>
        </el-form-item>

        <el-form-item label="总金额">
          <div class="total-amount">{{ orderForm.total_amount }} 元</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showOrderDialog = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">确认下单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeft, Picture, MapLocation,
  House, Food, WindPower, Sunny,
  HotWater, Connection, Monitor,
  Refrigerator
} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import common_util from "../../util/common_util.js";

const route = useRoute()
const router = useRouter()
const houseId = ref(Number(route.params.houseid))

// State
const house = ref({
  house: {},
  address: {},
  facility: {},
  images: {},
  reviews: {}
})

const showReviewDialog = ref(false)
const reviewForm = ref({
  cleanliness_rating: 5,
  location_rating: 5,
  facility_rating: 5,
  value_rating: 5,
  communication_rating: 5,
  comment: ''
})

const showOrderDialog = ref(false)
const orderForm = ref({
  start_date: '',
  end_date: '',
  total_amount: 0,
  deposit: 0
})

// Constants
const statusMap = {
  pending: { label: '待审核', type: 'warning' },
  published: { label: '已发布', type: 'success' },
  rented: { label: '已出租', type: 'info' },
  maintenance: { label: '维护中', type: 'warning' },
  offline: { label: '已下架', type: '' }
}

const facilityIcons = {
  has_wifi: Connection,
  has_tv: Monitor,
  has_ac: WindPower,
  has_heating: Sunny,
  has_kitchen: Food,
  has_washer: Refrigerator,
  has_lift: House,
  has_parking: House,
  has_water_heater: HotWater,
  has_refrigerator: Refrigerator
}

const facilityLabels = {
  has_wifi: '无线网络',
  has_tv: '电视',
  has_ac: '空调',
  has_heating: '暖气',
  has_kitchen: '厨房',
  has_washer: '洗衣机',
  has_lift: '电梯',
  has_parking: '停车位',
  has_water_heater: '热水器',
  has_refrigerator: '冰箱'
}

// Computed Properties
const galleryImages = computed(() => {
  const images = []
  if (house.value.images?.cover?.image_url) {
    images.push({
      ...house.value.images.cover,
      is_cover: true
    })
  }
  if (house.value.images?.gallery) {
    images.push(...house.value.images.gallery)
  }
  return images.length > 0 ? images : [{image_url: '', is_cover: false}]
})

const rentalDays = computed(() => {
  if (orderForm.value.start_date && orderForm.value.end_date) {
    const start = new Date(orderForm.value.start_date)
    const end = new Date(orderForm.value.end_date)
    const diffTime = Math.abs(end - start)
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  }
  return 0
})

const calculateTotalAmount = computed(() => {
  if (house.value.house?.price && rentalDays.value > 0) {
    const dailyPrice = house.value.house.price / 30
    return Math.round(dailyPrice * rentalDays.value)
  }
  return 0
})

// Methods
const fetchHouseDetail = async () => {
  try {
    const response = await axios.get(`/api/houses/${houseId.value}`)

    if (response.data.code === 0) {
      house.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取房源详情失败')
      if (response.data.code === 404) {
        router.push({ name: 'house-list' })
      }
    }
  } catch (error) {
    ElMessage.error('获取房源详情失败')
    console.error(error)
  }
}

const getAllImages = () => {
  return galleryImages.value.filter(img => img.image_url).map(img => img.image_url)
}

const getStatusLabel = (status) => {
  return statusMap[status]?.label || status
}

const getStatusTagType = (status) => {
  return statusMap[status]?.type || ''
}

const getFacilityIcon = (key) => {
  return facilityIcons[key] || House
}

const getFacilityLabel = (key) => {
  return facilityLabels[key] || key
}

const formatReviewTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const formatDate = (date) => {
  return date.toISOString().split('T')[0]
}

const getRatingLabel = (field) => {
  const labels = {
    cleanliness_rating: '清洁',
    location_rating: '位置',
    facility_rating: '设施',
    value_rating: '性价比',
    communication_rating: '沟通'
  }
  return labels[field] || field
}

const handlePageChange = (page) => {
  // Implement pagination logic here
  console.log('Page changed to:', page)
}

const openOrderDialog = () => {
  const today = new Date()
  const nextMonth = new Date(today)
  nextMonth.setMonth(nextMonth.getMonth() + 1)

  orderForm.value = {
    start_date: formatDate(today),
    end_date: formatDate(nextMonth),
    total_amount: calculateTotalAmount.value,
    deposit: house.value.house?.deposit || 0
  }
  showOrderDialog.value = true
}

const handleSubmitApplication = () => {
  openOrderDialog()
}

const submitOrder = async () => {
  try {
    if (!orderForm.value.start_date || !orderForm.value.end_date) {
      ElMessage.warning('请选择租赁日期')
      return
    }

    if (new Date(orderForm.value.end_date) <= new Date(orderForm.value.start_date)) {
      ElMessage.warning('结束日期必须大于开始日期')
      return
    }

    // 确保从房源数据中获取 landlord_id (userid)
    if (!house.value.house?.userid) {
      ElMessage.error('无法获取房东信息，请刷新页面重试')
      return
    }

    const payload = {
      house_id: houseId.value,
      landlord_id: house.value.house.userid, // 明确传递 landlord_id
      start_date: orderForm.value.start_date,
      end_date: orderForm.value.end_date,
      total_amount: calculateTotalAmount.value,
      deposit: house.value.house?.deposit || 0
    }

    console.log('提交订单数据:', payload) // 调试用

    const response = await axios.post('/api/orders', payload, {
      headers: common_util.accessHeader()
    })
    console.log("上一个页面的orderid"+response.data.data.order_id)
    if (response.data.code === 0) {
      ElMessage.success('订单创建成功')
      showOrderDialog.value = false
      router.push({
        name: 'order-detail',
        params: { orderId: response.data.data.order_id }
      })
    } else {
      ElMessage.error(response.data.msg || '订单创建失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push({ name: 'login' })
    } else {
      ElMessage.error(error.response?.data?.msg || '服务器错误')
    }
  }
}

const submitReview = async () => {
  try {
    const requiredFields = [
      'cleanliness_rating',
      'location_rating',
      'facility_rating',
      'value_rating',
      'communication_rating'
    ]

    for (const field of requiredFields) {
      if (!reviewForm.value[field]) {
        ElMessage.warning(`请填写${getRatingLabel(field)}评分`)
        return
      }
    }

    const payload = {
      houseid: houseId.value,
      ...reviewForm.value
    }

    const response = await axios.post('/api/reviews', payload, {
      headers: common_util.accessHeader()
    })

    if (response.data.code === 0) {
      ElMessage.success('评论提交成功')
      showReviewDialog.value = false
      reviewForm.value = {
        cleanliness_rating: 5,
        location_rating: 5,
        facility_rating: 5,
        value_rating: 5,
        communication_rating: 5,
        comment: ''
      }
      await fetchHouseDetail()
    } else {
      ElMessage.error(response.data.msg || '评论提交失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push({ name: 'login' })
    } else {
      ElMessage.error(error.response?.data?.msg || '服务器错误')
    }
  }
}

const goBack = () => {
  router.go(-1)
}

// Watchers
watch(() => [orderForm.value.start_date, orderForm.value.end_date], () => {
  orderForm.value.total_amount = calculateTotalAmount.value
})

// Lifecycle Hooks
onMounted(() => {
  fetchHouseDetail()
})
</script>

<style scoped>
.house-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px 20px;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  flex-wrap: wrap;
  gap: 15px;
}

.back-button {
  margin-right: 15px;
  padding: 10px 0;
}

.title {
  font-size: 24px;
  margin: 5px 0 0;
  font-weight: 600;
  color: #333;
  flex-grow: 1;
}

.status-tag {
  margin-left: 12px;
}

.status-tag .el-tag {
  font-size: 14px;
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 160px);
}

.content-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.content-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.tab-content {
  height: 100%;
  overflow-y: auto;
  padding-right: 10px;
}

.image-section {
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 350px;
}

.el-carousel {
  border-radius: 8px;
  height: 100%;
}

.el-carousel :deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  color: white;
}

.el-carousel :deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

.el-image {
  transition: transform 0.3s;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.el-image:hover {
  transform: scale(1.02);
}

.cover-badge {
  position: absolute;
  top: 15px;
  right: 15px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  z-index: 2;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.info-item {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
}

.info-item label {
  display: block;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.info-item div {
  font-size: 16px;
  font-weight: 500;
}

.description-section {
  margin-top: 24px;
  min-height: 100px;
}

.description-section h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.description-content {
  line-height: 1.6;
  color: #666;
  white-space: pre-line;
}

.address-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.address-item {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
}

.address-item label {
  display: block;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.address-item div {
  font-size: 16px;
  font-weight: 500;
}

.address-item.full-width {
  grid-column: span 3;
}

.map-container {
  height: 250px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
}

.map-placeholder .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.facility-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.facility-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.facility-item .available {
  color: #67C23A;
}

.facility-item .unavailable {
  color: #F56C6C;
  opacity: 0.6;
}

.facility-item .el-icon {
  font-size: 18px;
}

.review-section {
  padding: 12px 0;
  min-height: 200px;
}

.review-item {
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 6px;
  background-color: #fafafa;
  border: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  font-weight: 500;
}

.review-time {
  color: #999;
  font-size: 12px;
}

.review-comment {
  padding: 12px;
  background-color: white;
  border-radius: 4px;
  line-height: 1.6;
  font-size: 14px;
  color: #333;
  border-left: 3px solid #409EFF;
}

.no-reviews {
  padding: 40px 0;
  text-align: center;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-buttons .el-button {
  min-width: 150px;
  padding: 12px 24px;
  font-size: 16px;
}

.tab-content::-webkit-scrollbar {
  width: 6px;
}

.tab-content::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.tab-content::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

@media (max-width: 992px) {
  .house-detail-container {
    max-width: 95%;
  }

  .info-grid,
  .facility-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .address-section {
    grid-template-columns: repeat(2, 1fr);
  }

  .address-item.full-width {
    grid-column: span 2;
  }
}

@media (max-width: 768px) {
  .info-grid,
  .facility-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .address-section {
    grid-template-columns: 1fr;
  }

  .address-item.full-width {
    grid-column: span 1;
  }

  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .info-grid,
  .facility-grid {
    grid-template-columns: 1fr;
  }

  .image-section {
    height: 300px;
  }
}
</style>